package fr.mywiki.view.web.struts.action.entry;

import java.rmi.RemoteException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import fr.mywiki.business.search.SearchEntryManager;
import fr.mywiki.view.web.struts.form.entry.SearchEntryForm;

/**
 * Dispatch action class for the search of an entry.
 * 
 * @author tlombard
 */
public class SearchEntryAction extends DispatchAction {
	/**
	 * Inits and displays the search window.
	 */
	public ActionForward display(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse arg3) {
		SearchEntryForm form = (SearchEntryForm)actionForm;
		form.init();
		return mapping.findForward("display");
	}
	
	/**
	 * Tries to access the wanted entry.
	 */
	public ActionForward validate(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse arg3) throws RemoteException,
			SQLException {
		SearchEntryForm form = (SearchEntryForm)actionForm;
		String searchString = form.getSearchString();
		
		ArrayList answers = null;
		
		answers = new ArrayList(SearchEntryManager.searchByTitle(searchString));
		
		form.init();
		/* Entries have been found */
		if(answers == null || answers.isEmpty() || answers.size() > 1) {
			request.setAttribute(EntryListAction.LIST_ENTRIES_IDS,answers);
			request.setAttribute(EntryListAction.SEARCH_STRING,searchString);
			return mapping.findForward("displayEntryList");
		} else {
			request.setAttribute(EntryPageAction.ENTRY_ID,((Long)answers.get(0)));
			return mapping.findForward("displayEntry");
		}
	}
	
	public ActionForward createNewEntry(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse arg3) {
		return mapping.findForward("create");
	}
}
